package org.example.votingsystem.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.votingsystem.Admin.Admin;
import org.example.votingsystem.account.Result;
import org.example.votingsystem.dao.AdminDao;
import org.example.votingsystem.util.JWTUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/manageLogin")
public class ManageLogin extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("account");
        String password = req.getParameter("password");
//        检查管理员登录信息
        AdminDao adminDao = new AdminDao();
        Admin admin = new Admin();
        try {
            if (adminDao.checkAdmin(username, password)) {
                String token = JWTUtil.getToken(admin);
                admin = adminDao.findAccountById(username);
                admin.setToken(token);
                Result result = new Result(200, "登录成功", admin);
                resp.getWriter().print(new ObjectMapper().writeValueAsString(result));
            } else {
                Result result = new Result(401, "没有此账号", null);
                resp.getWriter().print(new ObjectMapper().writeValueAsString(result));
            }
        } catch (SQLException e) {
            Result result = new Result(500, "后端错误！", null);
            resp.getWriter().print(new ObjectMapper().writeValueAsString(result));
        }
    }
}
